/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.web.configurer.filter;

import com.arisgo.cloud.core.redis.UserInfo;
import com.arisgo.cloud.core.Constant;
import com.arisgo.cloud.core.token.config.TokenProperties;
import com.arisgo.cloud.core.url.UrlProperties;
import com.arisgo.cloud.core.utils.JwtUtil;
import com.google.common.collect.Maps;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Map;

import static com.arisgo.cloud.web.utils.ServletUtil.sendResponseError;
import static com.auth0.jwt.RegisteredClaims.AUDIENCE;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;

/**
 * @author Arisgo
 * @since 2024/6/10
 */
@Component
@AllArgsConstructor
public class AuthenticationFilter extends OncePerRequestFilter {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private final UrlProperties urlProperties;
    private final TokenProperties tokenProperties;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        // 默认开启鉴权
        if (tokenProperties.getEnabled()) {
            if (urlProperties.isSkipUrl(request.getServletPath())) {
                log.info("request path: {}", request.getServletPath());
                filterChain.doFilter(request, response);
                return;
            }

            // 鉴权
            if (!StringUtils.hasLength(authorization) || !JwtUtil.verify(authorization, tokenProperties.getTokenSecret())) {
                logger.error("鉴权失败，token异常。");
                sendResponseError(response, request.getServletPath(), UNAUTHORIZED);
                return;
            }
            String userId = JwtUtil.getClaim(authorization, AUDIENCE, String.class);
            String token = (String) redisTemplate.opsForHash().get(Constant.TOKEN_PREFIX + userId, Constant.ACCESS_TOKEN);
            if (!JwtUtil.getToken(authorization).equals(token)) {
                logger.error("鉴权失败，token失效");
                sendResponseError(response, request.getServletPath(), UNAUTHORIZED);
                return;
            }
        }
        if (StringUtils.hasLength(authorization)) {
            UserInfo user = JwtUtil.getClaim(authorization, Constant.LOGIN_USER, UserInfo.class);
            Map<String, Object> claims = Maps.newHashMap();
            claims.put(UserInfo.TENANT_ID, user.getTenantId());
            claims.put(UserInfo.USER_ID, user.getUserId());
            claims.put(UserInfo.STAFF_ID, user.getStaffId());
            request.setAttribute(Constant.LOGIN_USER, user);
            filterChain.doFilter(RequestParameterWrapper.creator(request, claims), response);
        } else {
            filterChain.doFilter(request, response);
        }

    }

}
